<template>
	<view class="install-container" style="margin-bottom: 30rpx;">
		<view @click="handleDelete" class="delete-icon">X</view>
		<!-- 用户信息 -->
		<!-- 如果需要使用 validateFunction 自定义校验规则,则不能采用 uni-forms 的 rules 属性来配置校验规则，
		这时候需要通过ref，在onReady生命周期调用组件的setRules方法绑定验证规则 -->
		<uni-forms :value="params" ref="form" validateTrigger="bind" class="word5">
			<uni-forms-item required label="耗材分类：" name="类型名称">
				<!-- <input maxlength="50" placeholder="请输入起始楼层号" v-model="params['起始楼层号']" @input="binddata('起始楼层号',$event.detail.value)"> -->
				<song-data-picker :localdata="classList" popup-title="请选择耗材分类" :openSearch="true" @change="onchange"
					@nodeclick="onnodeclick"></song-data-picker>
			</uni-forms-item>
			<uni-forms-item v-if="goodsList.length" required label="耗材名称：" name="物料id">
				<!-- <input type="number" maxlength="18" v-model="params['楼层数量']" placeholder="请输入申请单位" @input="binddata('楼层数量',$event.detail.value)" > -->
				<song-data-picker ref="songPicker" :localdata="goodsList" popup-title="请选择耗材" :openSearch="true"
					@change="onchange1" @nodeclick="onnodeclick"></song-data-picker>
			</uni-forms-item>
			<uni-forms-item v-show="materialInfo['规格型号']" required label="规格型号：" name="规格型号">
				<input disabled type="number" maxlength="18" v-model="materialInfo['规格型号']" placeholder="无"
					@input="binddata('楼层数量',$event.detail.value)">
			</uni-forms-item>
			<uni-forms-item v-show="materialInfo['计量单位']" required label="计量单位：">
				<input disabled type="text" maxlength="18" v-model="materialInfo['计量单位']" placeholder="无"
					@input="binddata('楼层数量',$event.detail.value)">
			</uni-forms-item>
			<uni-forms-item v-show="showInput" required label="采购单价：" name="单价">
				<input type="number" @input="handleInput" maxlength="18" v-model="materialInfo['单价']"
					placeholder="请输入采购单价">
			</uni-forms-item>
			<uni-forms-item required label="数量：" name="数量">
				<van-stepper @change="handleChange" input-width="120rpx" button-size="64rpx" :value="params['数量']"
					min="1" />
			</uni-forms-item>
			<uni-forms-item v-show="showInput" required label="采购总金额：" name="总价">
				<input @input="handleTotalInput" placeholder="请输入采购总金额" type="number" maxlength="18"
					v-model="params['总价']">
			</uni-forms-item>
			<!-- <uni-forms-item required label="所属楼栋：" name="楼栋id">
				<view :class="label == '请选择所属楼栋' ? 'color':''" class="tap" @click="handleTap('picker')">{{label}}</view>
				<lb-picker ref="picker" @click="handleTap('picker')" v-model="params['楼栋id']"
				 mode="selector" :list="buildList" :dataset="{ name: 'label' }" @confirm="handleConfirm" @cancel="handleCancel">
				</lb-picker>
			</uni-forms-item> -->
			<!-- <button class="material-form-btn" @click="submitForm">提交</button> -->

		</uni-forms>
		<view class="line"></view>
	</view>
</template>

<script>
	import LbPicker from '@/components/lb-picker/index.vue'
	import dayjs from 'dayjs'
	export default {
		components: {
			LbPicker
		},
		props: {
			params: {
				type: Object,
				default: () => {}
			},
			classList: {
				type: Array,
				default: () => []
			},
			storeId: {
				type: Number
			}
		},
		data() {
			return {
				showInput: false,
				materialInfo: {
					单价: 1
				},
				formValue: {},
				goodsList: [],
				label: '请选择所属楼栋',
				params2: {
					物料类别: null,
					所属机构: this.$config.groupId,
					所属仓库: null,
					pagination: {
						current: 1,
						pageSize: 1000
					},
					sorter: {
						field: "id",
						order: 0
					}
				},
				//表单验证规则
				rules: {
					类型名称: {
						rules: [{
							required: true,
							errorMessage: '请选择耗材分类',
						}]
					},
					物料id: {
						rules: [{
							required: true,
							errorMessage: '请选择耗材',
						}]
					},
					单价: {
						rules: [{
							required: true,
							errorMessage: '请填写单价',
						}]
					},
					总价: {
						rules: [{
							required: true,
							errorMessage: '请填写采购总金额',
						}]
					}
				}
			}
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rules)
		},
		onLoad(options) {
			this.params2.所属仓库 = +options.id
		},
		methods: {
			handleInput(e) {
				// this.params.总价 = parseInt(e.detail.value) * this.params.数量
				this.$emit('change', {
					id: this.params.id,
					price: parseInt(e.detail.value) * this.params.数量
				})
				this.materialInfo.总价 = parseInt(e.detail.value) * this.params.数量

				this.getFormData()
			},
			handleTotalInput(e) {
				this.$emit('change', {
					id: this.params.id,
					price: parseInt(e.detail.value)
				})
				this.materialInfo.单价 = parseInt(e.detail.value) / this.params.数量
				this.materialInfo.总价 = parseInt(e.detail.value)
				console.log(this.materialInfo.单价)

				this.getFormData()
			},
			handleDelete() {
				this.$emit('delete', this.params.id)
			},
			binddata(name, value) {
				// 通过 input 事件设置表单指定 name 的值
				this.$refs.form.setValue(name, value)
			},
			handleChange(event) {
				this.$emit('change', {
					id: this.params.id,
					price: (this.materialInfo.单价 * event.detail).toFixed(2)
				})
				this.$emit('changeNum', {
					id: this.params.id,
					num: event.detail
				})
				// this.params.数量 = event.detail
				this.materialInfo.数量 = event.detail
				this.materialInfo.总价 = this.materialInfo.单价 * event.detail
				this.getFormData()
			},
			onchange(e) {
				if (uni.getStorageSync('purchaseList')) {
					let purchaseList = uni.getStorageSync('purchaseList')
					const index = purchaseList.findIndex(item => item.id === this.params.id)
					console.log('index', index)
					if (index > -1) {
						purchaseList.splice(index, 1)
						uni.setStorageSync('purchaseList', purchaseList)
					}
				}
				this.$emit('changeClass', {
					id: this.params.id,
					value: e.detail.value[0].类型名称
				})
				this.materialInfo = {
					单价: null
				}
				this.showInput = false
				this.goodsList = []
				// const value = e.detail.value
				this.materialInfo.类型名称 = e.detail.value[0].类型名称
				this.params2.物料类别 = e.detail.value[0].类型id
				this.binddata('类型名称', e.detail.value[0].类型名称)
				// this.getFormData()
				// this.$emit('update:params', this.params)
				this.getGoodsList()
			},
			onchange1(e) {
				
				const value = e.detail.value[0]
				let id = e.detail.value[0].物料ID
				let purchaseList = uni.getStorageSync('purchaseList') || []
				const item = purchaseList.find(item => item.物料id === id)
				if (item) {
					uni.showToast({
						title: '列表中已有该耗材',
						icon: 'none'
					})
					this.$refs.songPicker.inputSelected = []
					return
				}
				this.showInput = true
				this.formValue.物料id = value.物料ID
				// this.materialInfo = value
				this.materialInfo.计量单位 = value.计量单位
				this.materialInfo.规格型号 = value.规格型号
				this.materialInfo.物料id = value.物料ID
				this.materialInfo.单价 = value.平均单价
				this.materialInfo.总价 = value.平均单价
				this.$emit('change', {
					id: this.params.id,
					price: value.平均单价
				})
				this.$emit('changeName', {
					id: this.params.id,
					value: value.物料ID
				})

				this.binddata('物料id', value.物料ID)
				this.getFormData()
			},
			async getGoodsList() {
				this.params2.所属仓库 = this.storeId
				const res = await this.$http.post('/property/consumable/list', this.params2)
				if (res.code === 10000) {
					console.log(res)
					res.data.list = res.data.list || []
					res.data.list.forEach(item => {
						item.text = item.物料名称
						item.value = item.物料ID
					})
					this.goodsList = res.data.list
					if (!this.goodsList.length) {
						uni.showToast({
							title: '当前分类无耗材',
							icon: 'none'
						})
					}
				}
			},
			getFormData() {
				
				let params = Object.assign({}, this.params, this.materialInfo)
				console.log('thisparams', this.params)
				if (params.单价 && params.总价) {
					this.binddata('单价', parseInt(params.单价))
					this.binddata('总价', parseInt(params.总价))
				}

				console.log('params', params)
				let purchaseItem = [{
					id: params.id,
					物料id: params.物料id,
					数量: params.数量,
					单价: parseInt(params.单价),
					总价: parseInt(params.总价)
				}]
				if (!uni.getStorageSync('purchaseList')) {
					uni.setStorageSync('purchaseList', purchaseItem)
				} else {

					let purchaseList = uni.getStorageSync('purchaseList')
					const index = purchaseList.findIndex(item => item.id === params.id)
					console.log('index', index)
					if (index > -1) {
						purchaseList[index] = purchaseItem[0]
						// console.log('触发了', index, applyList)
					} else {
						purchaseList = purchaseList.concat(purchaseItem)
					}
					uni.setStorageSync('purchaseList', purchaseList)
				}
				let list = uni.getStorageSync('purchaseList') || []
				this.$emit('total', list)
				
			},
			//校验表单，通过返回true，否则返回false
			validate() {
				this.$refs.form.submit().then(res => {
					console.log('res', res)
					// console.log('成功了')
				}).catch(err => {
					console.log('表单错误信息：', err);
					uni.showToast({
						icon: 'none',
						title: "表单字段填写错误，请检查"
					})
					return false
				})
				return true
			}
		}
	}
</script>

<style lang="scss" scoped>
	.delete-icon {
		display: flex;
		justify-content: flex-end;
		padding-right: 30rpx;
		font-size: 42rpx;
		color: #999;
	}

	.line {
		margin-top: 100rpx;
		// margin-bottom: 40rpx;
		width: 710rpx;
		margin-left: 20rpx;
		height: 2rpx;
		background-color: #ccc;
	}

	.install-container {
		// height: 100vh;
		// background-color: #F8F8F8;
	}

	.color {
		color: #808080;
	}

	.tap {
		display: flex;
		align-items: center;
	}
</style>
